package com.dt.module.om.util;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.concurrent.TimeUnit;


public class CronJob  implements Job {

    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 你的任务代码
        String cmd=context.getJobDetail().getJobDataMap().getString("process");
        System.out.println("任务执行: " + new Date()+",process:"+cmd);
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            //输出流处理
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
            String line;
            while((line = reader.readLine())!=null){
                System.out.println(line);
            }
            // 等待进程执行完成
            process.waitFor(60*30, TimeUnit.SECONDS);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    public static void addJob(String expr,String process) throws Exception {
        // 创建Scheduler
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        // 创建JobDetail
        JobDetail jobDetail = JobBuilder.newJob(CronJob.class)
                .withIdentity("cronJob", "group1")
                .usingJobData("process",process)
                .build();
        // 创建Trigger，模仿crontab的时间表达式
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("cronTrigger", "group1")
                .withSchedule(CronScheduleBuilder.cronSchedule(expr)) // 每5秒执行一次
                .build();
        // 绑定Job和Trigger
        scheduler.scheduleJob(jobDetail, trigger);
        // 启动Scheduler
        scheduler.start();
    }
    public static void main(String[] args) throws Exception {
        addJob("0/5 * * * * ?","sh /tmp/do.sh");
    }
}